package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrdersettingService;
import com.itheima.health.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {

    @Resource
    private OrdersettingService ordersettingService;

    /**
     *
     * @param file 上传的文件
     * @return 成功Result</u>类型，包含了是否成功的信息
     * @throws IOException 失败异常
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        String filename = file.getOriginalFilename();
        // xls 或 者 xlsx
        if (Objects.isNull(filename)) {
            throw new RuntimeException("文件名为空");
        }
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (!".xls".equals(suffix) && !".xlsx".equals(suffix)) {
            throw new RuntimeException("文件校驗失敗");
        }
        List<OrderSetting> list = ExcelUtils.excelToShopIdList(file.getInputStream()); // 解析文件获得数据
        // 准备添加到数据库
        ordersettingService.add(list);
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS);
    }
}
